package annotation;

import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author uiao
 * @Title: 自定义注解
 * @date 2018/8/315:39
 */
public class AnnotationTest {
    private static Logger logger = Logger.getLogger(AnnotationTest.class);

    public static void main(String[] args) {
        Company company = injectAnnotationValue(Company.class);
        // 打印输入注解后的值
        System.out.println("打印注入注解后的值 ==>>");
        System.out.println(company.toString());
    }

    public static Company injectAnnotationValue(Class<?> clazz) {
        Company company = new Company();
        // 遍历Class里使用的FIELD类型的注解

        for (Field field : clazz.getDeclaredFields()) {
            Phone phone = field.getAnnotation(Phone.class);
            if (phone != null) {
                System.out.println(clazz.getName() + "上使用了属性注解：" + field.getName() + "，注解的值为： " + phone.value());
                // 给company实例赋上注解的值
                company.setPhone(phone.value());
            }
        }
        // 遍历Class里使用的METHOD类型的注解
        for (Method method : clazz.getDeclaredMethods()) {
            City city = method.getAnnotation(City.class);
            if (city != null) {
                System.out.println(clazz.getName() + "上使用了方法注解：" + method.getName() + "，注解的值为： "
                        + " code: " + city.code()
                        + ", name: " + city.name());
                // 给company实例赋上注解的值
                company.setCityCode(city.code());
                company.setCityName(city.name());
            }
        }
        return company;
    }
}
